from random import randint

from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from meiduo_mall.libs.yuntongxun.sms import CCP
from . import constants
from celery_tasks.sms.tasks import send_sms_code

from django.shortcuts import render
import logging

logger = logging.getLogger('django')  # 创建日志输出器

# Create your views here.



class SMSCodeView(APIView):
    """发送短信验证码"""
    def get(self, request, mobile):
        """
        1.生成短信验证码
        2.创建redis连接对象，并且在dev配置中新建redis库
        3.把验证码存储到redis中
        4.利用容联云通讯发送短信
        :param request:
        :param mobile:
        :return:
        """
        # 0.创建redis连接对象
        redis_conn = get_redis_connection('verify_codes')
        # 1.60秒内不允许重新发送短信
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return Response({'message': '发送短信过于频繁'}, status=status.HTTP_400_BAD_REQUEST)

        # 3.生成短信验证码
        sms_code = '%06d' % randint(0, 999999)
        logger.info(sms_code)

        # 创建redis管道对象
        pl = redis_conn.pipeline()

        # 4.把验证码存储到redis中
        # redis_conn.setex(key, 过期时间, value)
        # redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)

        # 5.存储此手机号已发送短信标记
        # redis_conn.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)

        # 执行管道
        pl.execute()

        # 6.利用容联云通讯发送短信
        # CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES // 60], 1)
        # 触发异步任务
        send_sms_code.delay(mobile, sms_code)

        # 7.响应
        return Response({'message': 'OK'})
